const router = require('koa-router')()
const jwt = require('jsonwebtoken')
const verify = require('jsonwebtoken/verify')
const { JWTSECRET } =  require('../conf/constants')

router.prefix('/users')

router.get('/', function (ctx, next) {
  ctx.body = 'this is a users response!'
})

router.get('/bar', function (ctx, next) {
  ctx.body = 'this is a users/bar response'
})

router.post('/login', async (ctx, next) => {
  const { userName, password } = ctx.request.body
  let userInfo
  if (userName == 'zhangsan' && password == 'abc') {
    userInfo = {
      userName,
      nickname:'张三',
      gender: 1,
      uid: 1,
    }
    const token = jwt.sign(userInfo, JWTSECRET, {
      expiresIn: '1h'
    })
    ctx.body = {
      errno: 0,
      data: token,
    }
  } else {
    ctx.body = {
      errno: 1,
      data: '登录失败',
    }
  }

})

router.get('/getUserInfo', async (ctx, next) => {
  const authorization  = ctx.headers.authorization
  console.log('authorization', authorization)
  try {
    const userInfo = await verify(authorization.split(' ')[1], JWTSECRET)
    ctx.body = {
      errno: 1,
      data: userInfo
    }
  } catch (error) {
    console.log(error)
    ctx.body = {
      errno: -1,
      data:'获取用户信息失败'
    }
  }

})

module.exports = router
